import {useDispatch, useSelector} from "react-redux";
import {useEffect, useState} from "react";

function useInitState(action, key, afterAction = () => null) {
  const dispatch = useDispatch()
  // 维护loading状态
  // useRequest
  const [loading, setLoading] = useState(true);
  // 维护error状态
  const [err, setErr] = useState(null)
  const userInfo = useSelector(state => {
    return state[key]
  })
  useEffect(() => {
    dispatch(action()).then(res => {
      // 接口请求完成之后的操作，方法由外部组件进行传入
      afterAction()
      // 设置loading状态
      setLoading(false)
    }, err => {
      setErr(err)
    })
  }, [])
  return {
    ...userInfo,
    loading,
    error: err
  }
}

export default useInitState
